<template>
	<div class="system-dic-container layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<div class="system-user-search mb15" style="align-items: self-start;">
				<el-input size="default" placeholder="请输入用户账号" style="width: 180px;"
					v-model="state.tableData.param.param.nickname.val"> </el-input>
				<el-select v-model="state.tableData.param.param.company_id.val" filterable placeholder="请选择所属公司" clearable
					size="default" style="width: 180px;">
					<el-option v-for="(item) in state.platsData.company" :key="item.id" :label="item.title"
						:value="item.id"></el-option>
				</el-select>
				<el-select v-model="state.tableData.param.param.plat_id.val" filterable placeholder="请选择所属平台" clearable
					size="default" style="width: 180px;">
					<el-option v-for="(item) in state.platsData.palt" :key="item.id"
						:label="item.cname"
						:value="item.id"></el-option>
				</el-select>
				<el-select v-model="state.tableData.param.param.platform_id.val" filterable placeholder="请选择所属渠道" clearable
					size="default" style="width: 180px;">
					<el-option v-for="(item) in state.platsData.paltform" :key="item.id"
						:label="item.cname"
						:value="item.id"></el-option>
				</el-select>
				<el-select v-model="state.tableData.param.param.user_agent.val" filterable placeholder="请选择设备类型" clearable size="default" style="width: 180px;">
					<el-option v-for="item in state.uaList" :key="item.id" :label="item.cname" :value="item.id"></el-option>
				</el-select>
				<el-input size="default" placeholder="子渠道名称" style="width: 180px;"
					v-model="state.tableData.param.param.offer_name.val"> </el-input>

				<el-input size="default" placeholder="调查ID" style="width: 180px;" clearable
					v-model="state.tableData.param.param.offerid.val"> </el-input>
				<el-input size="default" placeholder="唯一标识" type="textarea" rows="1" style="width: 180px;"
					v-model="state.tableData.param.param.tx_id.val"> </el-input>
				<el-input size="default" placeholder="请输入IP" style="width: 180px;"
					v-model="state.tableData.param.param.ip.val"> </el-input>
				<el-input size="default" placeholder="请输入国家" style="width: 180px;"
					v-model="state.tableData.param.param.ip_code.val"> </el-input>
				<el-select v-model="state.timeType" filterable placeholder="请选择时间筛选类型" clearable
					size="default" style="width: 180px;" @change="changeTimeType">
					<el-option label="回调时间" value="1"></el-option>
					<el-option label="实际核减时间" value="2"></el-option>
				</el-select>
				<!-- 答题时间 -->
				<el-date-picker size="default" style="width: 280px;" v-model="state.tableData.param.param.create_time.val" v-if="state.timeType == '1'"
					type="daterange" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间"
					:default-time="[new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]" value-format='X' />
				<!-- 核减答题时间 -->
				<el-date-picker size="default" style="width: 280px;" v-model="state.tableData.param.param.before_time.val" v-if="state.timeType == '2'"
					type="daterange" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间"
					:default-time="[new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]" value-format='X' />
				<el-select v-model="state.tableData.param.param.status.val" placeholder="请选择答题状态" clearable size="default" v-if="state.timeType == '1'"
					style="width: 180px;">
					<el-option label="数据统计" value="abcd"></el-option>
					<el-option label="答题成功" value="1"></el-option>
					<el-option label="批准" value="approval"></el-option>
					<el-option label="答题失败" value="0"></el-option>
					<el-option label="核减" value="2"></el-option>
				</el-select>
				<el-button size="default" type="primary" @click="seachClick">
					<el-icon>
						<ele-Search />
					</el-icon>
					查询
				</el-button>
				<el-button size="default" type="primary" v-auth="'/finance/record/download'" :loading="state.daochulodding"
					@click="deriveCompany()">
					<el-icon>
						<ele-Download />
					</el-icon>
					导出
				</el-button>
				<el-upload class="upload-demo" :auto-upload="false" :on-change="onChange" :show-file-list="false"
					accept=".csv, .xls, .xlsx">
					<el-button size="default" type="primary" v-auth="'/finance/record/account_file'">
						<el-icon>
							<ele-Upload />
						</el-icon>
						上传
					</el-button>
				</el-upload>
				<el-upload class="upload-demo" :auto-upload="false" :on-change="onChangePz" :show-file-list="false"
					accept=".csv, .xls, .xlsx">
					<el-button size="default" type="primary" v-auth="'/finance/record/approval_file'">
						<el-icon>
							<ele-Upload />
						</el-icon>
						上传批准
					</el-button>
				</el-upload>
			</div>
			<div class="tip custom-block">
				<p class="custom-block-title">总积分：<span style="color:#e75141">{{ state.tableData.total_money }}</span>Points</p>
				<div v-if="state.statisticsData" style="display: flex; align-items: center;flex-wrap: wrap;flex: 1;justify-content: right;">
					<p class="ml20">成功数量：<span style="color: #4CAF50;">{{ state.statisticsData.is_count }}</span></p>
					<p class="ml20">核减数量：<span style="color: #F44336;">{{ state.statisticsData.the_count }}</span></p>
					<p class="ml20" v-if="state.statisticsData.approval_count">批准数量：<span style="color: #00BCD4;">{{ state.statisticsData.approval_count }}</span></p>
					<p class="ml20" v-if="state.statisticsData.approval_count">批准核减数占比：<span style="color: #FF9800;">{{ (state.statisticsData.the_count / (state.statisticsData.the_count + state.statisticsData.approval_count) * 100).toFixed(2) }}%</span></p>
					<p class="ml20">成功核减数占比：<span style="color: #FF9800;">{{ Number(state.statisticsData.is_count) == 0? 0 : (state.statisticsData.the_count / state.statisticsData.is_count * 100).toFixed(2) }}%</span></p>
					<p class="ml20">成功积分：<span style="color: #4CAF50;">{{ state.statisticsData.is_pay.toFixed(2) }}</span></p>
					<p class="ml20">核减积分：<span style="color: #F44336;">{{ (state.statisticsData.the_pay * -1).toFixed(2) }}</span></p>
					<p class="ml20">实际积分：<span style="color: #2196F3;">{{ state.statisticsData.total_pay.toFixed(2) }}</span></p>
					<p class="ml20" v-if="state.statisticsData.approval_pay">批准积分：<span style="color: #00BCD4;">{{ (state.statisticsData.approval_pay).toFixed(2) }}</span></p>
					<p class="ml20" v-if="state.statisticsData.approval_pay">批准核减率：<span style="color: #FF9800;">{{ (state.statisticsData.the_pay*-1 / (state.statisticsData.approval_pay + state.statisticsData.the_pay*-1) * 100).toFixed(2) }}%</span></p>
					<p class="ml20">成功核减率：<span style="color: #FF9800;">{{ Number(state.statisticsData.is_pay) == 0? 0 : (state.statisticsData.the_pay / state.statisticsData.is_pay * 100 * -1).toFixed(2)}}%</span></p>
				</div>
			</div>
			<el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%">
				<el-table-column prop="id" label="ID" show-overflow-tooltip width="80px"></el-table-column>
				<el-table-column prop="user_name" label="用户账号" show-overflow-tooltip></el-table-column>
				<el-table-column prop="nickname" label="用户昵称" show-overflow-tooltip></el-table-column>
				<el-table-column label="公司名称" show-overflow-tooltip>
					<template #default="scope">
						{{ scope.row.company_name || '公海用户' }}
					</template>
				</el-table-column>
				<el-table-column prop="plat_name" label="平台名称" show-overflow-tooltip>
					<template #default="scope">
						{{ scope.row.plat_name || '-' }}
					</template>
				</el-table-column>
				<el-table-column prop="platform_name" label="渠道名称" show-overflow-tooltip>
					<template #default="scope">
						{{ scope.row.platform_name || '-' }}
					</template>
				</el-table-column>
				<el-table-column prop="offer_name" label="子渠道名称" show-overflow-tooltip></el-table-column>
				<el-table-column label="优惠id" width="100px" show-overflow-tooltip>
					<template #default="scope">
						<span style="cursor: pointer;" @click="getCountId(scope.row)">{{ scope.row.offerid }}</span>
					</template>
				</el-table-column>

				<!-- <el-table-column label="优惠id次数/日" width="100px">
					<template #default="scope">
						<el-button size="small" text type="primary" v-if="scope.row.offerid"
							@click="getCountId(scope.row)" :loading="scope.row.idCountLoadding">{{scope.row.idCount != null ? scope.row.idCount : '查询'}}</el-button>
						<template v-else>
							-
						</template>
					</template>
				</el-table-column> -->
				<el-table-column prop="ip" label="IP" width="150px" align="center" show-overflow-tooltip>
					<template #default="scope">
						<span style="cursor: pointer;" @click="goip(scope.row.ip)">{{ scope.row.ip || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column label="国家" width="60px" align="center">
					<template #default="scope">
						<span>{{ scope.row.ip_code || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="pay" label="积分(Points)" width="150px" align="center">
					<template #default="scope">
						<span
							:style="{ color: scope.row.status == 1 ? '#67C23A' : scope.row.status == 2 ? '#F56C6C' : '#000' }">{{
								scope.row.pay }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="user_agent" label="浏览器UA" show-overflow-tooltip ></el-table-column>
				<el-table-column label="完成时间" align="center" width="180px">
					<template #default="scope">
						<span>{{ dateFormatYMDHMS(scope.row.create_time * 1000) }}</span>
					</template>
				</el-table-column>
				<el-table-column label="回传状态" show-overflow-tooltip width="180px">
					<template #default="scope">
						<div class="xiaojiujiudiv">
							<div class="xiaojiujiu"
								:style="{ backgroundColor: scope.row.status == 1 ? (scope.row.danger ? '#6d6e87' : '#67C23A') : scope.row.status == 2 ? '#E6A23C' : '#F56C6C' }">
							</div>
							<div style="display: flex;align-items: center;" v-if="scope.row.status == 1">
								<span>答题完成{{ scope.row.approval ? ' - 批准' : '' }}</span>
								<el-tooltip class="box-item" content="请注意！间隔时间过短，开放题雷同，请认真完成，避免核减！" placement="top-start">
									<SvgIcon name="ele-WarningFilled" :size="16" color="#6d6e87" class="ml5"
										v-if="scope.row.danger" />
								</el-tooltip>
							</div>
							<span v-else-if="scope.row.status == 0">{{ scope.row.term_reason }}</span>
							<span v-else >
									{{(scope.row.before_time?dateFormatMDHMS(scope.row.before_time * 1000):'核减')}}<br v-if="scope.row.term_reason">
									{{ scope.row.term_reason ? (hejianDataJson[scope.row.term_reason] || scope.row.term_reason) : '' }}
							</span>
							<span v-if="scope.row.idCount"> - {{ scope.row.idCount }}</span>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
				:pager-count="5" :page-sizes="[10, 50, 100]" v-model:current-page="state.tableData.param.page" background
				v-model:page-size="state.tableData.param.limit" layout="total, sizes, prev, pager, next, jumper"
				:total="state.tableData.total">
			</el-pagination>
		</el-card>
	</div>
</template>

<script setup name="record">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { recordApi } from '/@/api/record/index';
import commonFunction from '/@/utils/commonFunction';
// 定义变量内容
const { dateFormatYMDHMS, dateFormatMDHMS } = commonFunction();
import { commApi } from '/@/api/comm/index';
const router = useRouter();
import goip from '/@/utils/goip.js'
const paramOp = {
	create_time: 'time',
	before_time: 'time',
	tx_id: '%%',
	offer_name: '%%',
	offerid:'%%',
	user_agent:'%%',
}
const state = reactive({
	timeType:"1",
	daochulodding: false,
	statisticsData:null,
	searchTime: [],
	platsData: {
		company: [],
		palt: [],
		paltform: []
	},
	uaList: [
		{ id: 'windows', cname: 'Windows' },
		{ id: 'mac', cname: 'Mac' },
		{ id: 'android', cname: 'Android' },
		{ id: 'iphone', cname: 'Iphone' },
		{ id: 'ipad', cname: 'Ipad' },
		{ id: 'linux', cname: 'Linux' },
		{ id: 'other', cname: '其他' }
	],
	tableData: {
		total_money: 0,
		data: [],
		total: 0,
		loading: false,
		param: {
			param: {
				nickname: {},
				company_id: {},
				plat_id: {},
				platform_id: {},
				ip: {},
				ip_code:{},
				tx_id: {},
				status: {},
				create_time: {},
				offerid: {},
				offer_name: {},
				before_time:{},
				user_agent:{}
			},
			page: 1,
			limit: 10,
		},
	},
});
const getPlats = () => {
	commApi().getPlats().then(res => {
		state.platsData = res.data
	})
}
const changeTimeType = (val) => {
	if(val == '1'){
		state.tableData.param.param.create_time = JSON.parse(JSON.stringify(state.tableData.param.param.before_time))
		state.tableData.param.param.before_time = {}
		state.tableData.param.param.status = {}
	}else if(val == '2'){
		state.tableData.param.param.before_time = JSON.parse(JSON.stringify(state.tableData.param.param.create_time))
		state.tableData.param.param.create_time = {}
		state.tableData.param.param.status = {}
	}else{
		state.tableData.param.param.before_time = {}
		state.tableData.param.param.create_time = {}
		state.tableData.param.param.status = {}
	}
}
/**
 * 文件选择改变时触发
 */
const onChange = (file) => {
	if (file.status !== "ready") return;

	const extension = file.raw.name.split('.').pop();
	const allowedExtensions = ['csv', 'xls', 'xlsx'];
	if (!allowedExtensions.includes(extension)) {
		ElMessage.error('Only CSV, XLS, and XLSX files are allowed');
		return false; // Prevent upload
	}

	const formData = new FormData();
	formData.append('file', file.raw);
	recordApi().account_file(formData).then(res => {
		ElMessage.success('上传成功');
		getTableData();
	})
}
/**
 * 文件选择改变时触发
 */
 const onChangePz = (file) => {
	if (file.status !== "ready") return;

	const extension = file.raw.name.split('.').pop();
	const allowedExtensions = ['csv', 'xls', 'xlsx'];
	if (!allowedExtensions.includes(extension)) {
		ElMessage.error('Only CSV, XLS, and XLSX files are allowed');
		return false; // Prevent upload
	}

	const formData = new FormData();
	formData.append('file', file.raw);
	recordApi().approval_file(formData).then(res => {
		ElMessage.success('上传成功');
		getTableData();
	})
}
const hejianDataJson = {
	'Inconsistent response':'质量终止',
	'suspect_response_pattern':'可疑响应模式',
	'open_ended_response':'开放题质量终止',
	'quality_termination_other':'其他质量终止',
	"Poor OE, Inconsistent response, Bot/programmatic fraud":'OE验证机器人欺诈',
	"Poor OE":'OE验证不通过',
}
// 初始化表格数据
const getTableData = async () => {
	state.tableData.loading = true;
	for (let key in state.tableData.param.param) {
		if (state.tableData.param.param[key].val && state.tableData.param.param[key].val !== '') {
			state.tableData.param.param[key].op = paramOp[key] || '='
		} else {
			state.tableData.param.param[key] = {}
		}
	}
	if(state.tableData.param.param.status.val && state.tableData.param.param.status.val == 'abcd' && state.tableData.param.param.create_time.val){
		getDataDDetail()
	}else{
		state.statisticsData = null
	}
	let updata_param = JSON.parse(JSON.stringify(state.tableData.param))
	if(updata_param.param.status.val && updata_param.param.status.val == 'approval'){
		updata_param.param.status = {}
		updata_param.param.approval = {}
		updata_param.param.approval.val = "0"
		updata_param.param.approval.op = ">"
	}

	try {
		// 请求当前页、前一页和后一页的数据
		const [currentPageData, prevPageData, nextPageData] = await Promise.all([
			recordApi().index(updata_param),
			state.tableData.param.page > 1 ? recordApi().index({ ...updata_param, page: updata_param.page - 1 }) : Promise.resolve({ data: { list: [] } }),
			recordApi().index({ ...updata_param, page: updata_param.page + 1 })
		]);
		currentPageData.data.list = currentPageData.data.list || []
		prevPageData.data.list = prevPageData.data.list || []
		nextPageData.data.list = nextPageData.data.list || []
		// 合并数据并标记危险记录
		const allData = [
			...currentPageData.data.list,
			...prevPageData.data.list,
			...nextPageData.data.list
		];
		markDanger(allData);

		// 仅渲染当前页数据
		state.tableData.data = currentPageData.data.list;
		// 更新状态
		state.tableData.total = currentPageData.data.total;
		state.tableData.total_money = currentPageData.data.total_pay;
	} catch (error) {
		console.error("数据加载失败", error);
	} finally {
		state.tableData.loading = false;
	}
};
//获取各个数据详情统计
const getDataDDetail = async() => {
	try {
		let res = await recordApi().get_ratio(state.tableData.param)
		state.statisticsData = res.data
	} catch (error) {
		
	}
	
}

const twoMinutesInSeconds = 300;
const markDanger = (data) => {
	// 先按 user_id 和 platform_id 对数据进行分组
	const groupedData = data.reduce((acc, item) => {
		if (item.status === 1) { // 只考虑 status 为 1 的记录
			const key = `${item.user_id}-${item.platform_id}`;
			if (!acc[key]) {
				acc[key] = [];
			}
			acc[key].push(item);
		}
		return acc;
	}, {});

	// 对每组数据进行检查
	Object.keys(groupedData).forEach(key => {
		const items = groupedData[key];
		// 对每一组数据进行比较
		for (let i = 0; i < items.length; i++) {
			for (let j = i + 1; j < items.length; j++) {
				const item1 = items[i];
				const item2 = items[j];
				const timeDifference = Math.abs(item1.create_time - item2.create_time);
				if (timeDifference < twoMinutesInSeconds) {
					item1.danger = true;
					item2.danger = true;
				}
			}
		}
	});
	return data;
}
//导出
const deriveCompany = async () => {
	ElMessageBox.confirm(`确认导出?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		for (let key in state.tableData.param.param) {
			if (state.tableData.param.param[key].val && state.tableData.param.param[key].val !== '') {
				state.tableData.param.param[key].op = paramOp[key] || '='
			} else {
				state.tableData.param.param[key] = {}
			}
		}
		state.daochulodding = true
		try {
			let data = JSON.parse(JSON.stringify(state.tableData.param))
			delete data.page
			delete data.limit
			if(data.param.status.val && data.param.status.val == 'approval'){
				data.param.status = {}
				data.param.approval = {}
				data.param.approval.val = 0
				data.param.approval.op = ">"
			}
			let res = await recordApi().download({ sort: 'id', order: 'desc', ...data })
			if (res) {
				// 假设 data 是返回来的二进制数据
				const url = window.URL.createObjectURL(new Blob([res], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }))
				const link = document.createElement('a')
				link.style.display = 'none'
				link.href = url
				link.setAttribute('download', new Date().toLocaleString() + '.xlsx')
				document.body.appendChild(link)
				link.click()
				document.body.removeChild(link)
			}
		} catch (error) {

		}
		state.daochulodding = false
	}).catch(() => { });
}
let clickIdCount = 0
let clickIdTimer = null
//查询次数
const getCountId = async (row) => {
	clickIdCount++;
	if (clickIdCount === 1) {
		clickIdTimer = setTimeout(async() => {
			// 获取当前日期
			const today = new Date(row.create_time * 1000);
			// 获取今天的第一秒（00:00:00）
			const startOfDay = new Date(today.setHours(0, 0, 0, 0));
			// 获取今天的最后一秒（23:59:59）
			const endOfDay = new Date(today.setHours(23, 59, 59, 999));
			// 获取时间戳并转换为秒（保留 10 位）
			const startTimestamp = Math.floor(startOfDay.getTime() / 1000);
			const endTimestamp = Math.floor(endOfDay.getTime() / 1000);
			let seachData = {
				"param": {
					"company_id": {
						"val": row.company_id,
						"op": "="
					},
					"create_time": {
						"val": [
							startTimestamp + '',
							endTimestamp + ''
						],
						"op": "time"
					},
					"offerid": {
						"val": row.offerid,
						"op": "="
					},
					"status": {
						"val": 1,
						"op": "="
					}
				}
			}
			row.idCountLoadding = true
			try {
				let resCount = await recordApi().get_count_id(seachData)
				if (resCount.code == 0) {
					row.idCount = resCount.data.total
				}
			} catch (error) {

			}
			row.idCountLoadding = false
			clickIdCount = 0;
		}, 300); // 300ms 作为区分单击和双击的时间间隔
	} else if (clickIdCount === 2) {
		clearTimeout(clickIdTimer);
		// state.tableData.param.param.offerid.val = row.offerid
		// seachClick()
		router.push({ path: '/finance/record', query: { id:row.offerid } })
		clickIdCount = 0;
	}
}
const seachClick = () => {
	onHandleCurrentChange(1)
}
// 分页改变
const onHandleSizeChange = (val) => {
	state.tableData.param.limit = val;
	getTableData();
};
// 分页改变
const onHandleCurrentChange = (val) => {
	state.tableData.param.page = val;
	getTableData();
};
// 页面加载时
onMounted(() => {
	let data = router.currentRoute.value.query;
	if(data && data.id){
		state.tableData.param.param.offerid.val = data.id
	}
	getTableData();
	getPlats();
});
</script>
<style lang="scss" scoped>
.xiaojiujiudiv {
	width: 100%;
	display: flex;
	align-items: center;

	.xiaojiujiu {
		width: 10px;
		height: 10px;
		border-radius: 50%;
		margin-right: 5px;
		flex: none;
	}

	span {
		flex: 1;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
}

.custom-block.tip {
	padding: 8px 16px;
	background-color: rgba(7, 215, 114, 0.1);
	border-radius: 4px;
	border-left: 5px solid var(--el-color-primary);
	display: flex;
	align-items: center;
	justify-content: space-between;
}
</style>
